using Aspire.Hosting;
using AspireApp9.AppHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Projects;

var builder = DistributedApplication.CreateBuilder(args);

var healthyAfter = DateTime.Now.AddSeconds(40);
builder.Services.AddHealthChecks().AddCheck(
    "delay40secs",
    () => DateTime.Now > healthyAfter
        ? HealthCheckResult.Healthy()
        : HealthCheckResult.Unhealthy()
    );

//添加withlifetime；可以避免healthcheck验证redis报unhealthy；导致整个项目启动不了
//StackExchange.Redis.RedisConnectionException: It was not possible to connect to the redis server(s). Error connecting right now. To allow this multiplexer to continue retrying until it's able to connect, use abortConnect=false in your connection string or AbortOnConnectFail=false; in your code.
//var cache = builder.AddRedis("cache").WithLifetime(ContainerLifetime.Persistent);//.WithHealthCheck("delay40secs");//.WithEnvironment("abortConnect", "false")

//var cache = builder.AddRedis("redis",32791).WithContainerName("redis-5e7c121b").WithLifetime(ContainerLifetime.Persistent);
var cache = builder.ExecutionContext.IsRunMode
    ? builder.AddRedis("cache").WithLifetime(ContainerLifetime.Persistent)
    : builder.AddConnectionString("cache");

var apiService = builder.AddProject<Projects.AspireApp9_ApiService>("apiservice").WithReplicas(2);

//builder.AddProject<Projects.AspireApp9_Web>("webfrontend")
//    .WithExternalHttpEndpoints()
//    .WithReference(cache)
//    .WaitFor(cache)//.WaitForCompletion(cache)
//    .WithReference(apiService)
//    .WaitFor(apiService)
//    .WithReplicas(2);

#region 添加容器+参数-暂不能访问
//参考docker命令：docker run --rm -it -p 8000:8080 -e ASPNETCORE_HTTP_PORTS=8080 mcr.microsoft.com/dotnet/samples:aspnetapp
//不加WithLifetime方法，容器不能访问
var value = builder.AddParameter("httpport", "8080");
var containerapp = builder.AddContainer("frontend", "mcr.microsoft.com/dotnet/samples", "aspnetapp") //从映像创建名为 的容器资源
       .WithEnvironment("ASPNETCORE_HTTP_PORTS", "8080")
       .WithHttpEndpoint(port: 8700, targetPort: 8080, null, null, true).WithLifetime(ContainerLifetime.Persistent); //通过将主机绑定到端口 8700 并将其映射到容器的端口 8080 来公开终结点
#endregion

var webapi = builder.AddProject<Projects.WebApi>("webapi");

#region 自定义集成
//var containerapp1 = builder.AddResourceContainerDev("maildev").WithLifetime(ContainerLifetime.Persistent);
#endregion

builder.AddProject<Projects.AspireApp9_Web>("webfrontend")
    .WithExternalHttpEndpoints()
    .WithReference(cache)
    .WaitFor(cache)//.WaitForCompletion(cache)
    .WithReference(apiService)
    .WaitFor(apiService)
    .WithReference(webapi)
    .WaitFor(webapi)
    .WithReplicas(2);



builder.Build().Run();
